// eventModel.go
package models

import (
	"context"
	"fmt"

	//"time"
	"log"
	"myk8s/common"
	"sort"
	"strings"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type Events struct {
	EventType  string `json:"eventType"` //事件类型 warnning
	Kind       string `json:"kind"`      //对象类型 pod or deployment
	ObjName    string `json:"objName"`   //对象：pod的名称
	Message    string `json:"message"`   //信息
	Reason     string `json:"reason"`    //原因、内容
	CreateTime string `json:"createTime"`
}

func EventList(kubeconfig, namespace, kind, objName string, limitd int64) ([]Events, error) {
	clientset := common.ClientSet(kubeconfig)
	var err error
	var events *corev1.EventList

	var listOptions = metav1.ListOptions{}
	if limitd > 0 {
		listOptions = metav1.ListOptions{
			Limit: limitd,
		}
	}

	if kind != "" && objName != "" {
		listOptions = metav1.ListOptions{
			FieldSelector: fmt.Sprintf("involvedObject.name=%s", objName),
			TypeMeta:      metav1.TypeMeta{Kind: fmt.Sprintf("%s", kind)},
		}
		events, err = clientset.CoreV1().Events(namespace).List(context.TODO(), listOptions)
	} else if kind != "" && objName == "" {
		listOptions = metav1.ListOptions{
			TypeMeta: metav1.TypeMeta{Kind: fmt.Sprintf("%s", kind)},
		}
		events, err = clientset.CoreV1().Events(namespace).List(context.TODO(), listOptions)
	} else {
		events, err = clientset.CoreV1().Events(namespace).List(context.TODO(), listOptions)
	}
	if err != nil {
		log.Printf("list deployment error, err:%v\n", err)
	}

	lessFunc := func(i, j int) bool {
		return events.Items[j].CreationTimestamp.Before(&events.Items[i].CreationTimestamp)
	}
	sort.SliceStable(events.Items, lessFunc)

	var bbb = make([]Events, 0)
	for _, item := range events.Items {

		if objName != "" && kind == "" {
			if !strings.Contains(item.InvolvedObject.Name, objName) {
				continue
			}
		}

		Items := &Events{
			EventType:  item.Type,
			Kind:       item.InvolvedObject.Kind,
			ObjName:    item.InvolvedObject.Name,
			Message:    item.Message,
			Reason:     item.Reason,
			CreateTime: item.CreationTimestamp.Format("2006-01-02 15:04:05"),
		}
		bbb = append(bbb, *Items)
		//log.Println(item)
	}

	return bbb, err
}
